from flask import request, jsonify, current_app,session  # 从Flask框架中导入相关模块
from app import redis, db  # 导入redis数据库实例，SQLAlchemy数据库实例，和Flask管理模块
from app.api_v1_0 import api  # 导入API蓝图
from app.models import User, UserApply  # 导入用户模型

from app.utils.response_code import RET  # 导入自定义的响应码
from datetime import datetime, timedelta
import pytz

import json

from sqlalchemy.exc import IntegrityError  # 导入SQLAlchemy中的异常类，用于捕获数据库完整性错误
from app import constants

@api.route('test3', methods=["POST", "GET"])
def test3():
    print("enter")
    return "yes"

@api.route('who_i', methods=["POST"])
def get_i():
    print('enter')
    data = {
        'power':None,
        'name':None,
        'count':None,
        'admin':None,
        'user':None
    }

    data['power'] = session.get('power')
    data['name'] = session.get('name')



    try:
        data['count'] = db.session.query(User).count()
        data['admin'] = db.session.query(User).filter(User.power=='admin').count()
        data['user'] = db.session.query(User).filter(User.power=='user').count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取用户信息失败")

    # print("check:", data['power'], data['name'], data['count'], data['admin'], data['user'])

    return jsonify(errno=RET.OK, errmsg="查询成功", data=data)

@api.route('all_users', methods=["POST"])
def get_users():

    name = request.get_json().get('name')
    print('__________________', name)

    try:
        if name == '':
            data = db.session.query(User).all()
        else:
            data = db.session.query(User).filter(User.name.like(name + '%')).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取用户表信息失败")

    end = []

    for user in data:
        end.append({
            "id": user.id,
            "name": user.name,
            "mobile": user.mobile,
            "power": user.power,
            "mail": user.mail,
            "login_time": user.login_time.strftime('%Y-%m-%d %H:%M:%S'),
            "create_time": user.create_time.strftime('%Y-%m-%d %H:%M:%S')
        })

    return jsonify(errno=RET.OK, errmsg="查询成功", data=end)



@api.route('changePower', methods=["POST"])
def change_power():
    id = request.get_json().get('id')
    power = request.get_json().get('power')
    # print("传入的是******", id, power)

    try:

        aim = db.session.query(User).get(id)
        aim.power = 'user' if power == 'admin' else 'admin'  # 切换权限

        data = db.session.query(User).all()

        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取用户表信息失败")

    end = []

    for user in data:
        end.append({
            "id": user.id,
            "name": user.name,
            "mobile": user.mobile,
            "power": user.power,
            "mail": user.mail,
            "login_time": user.login_time.strftime('%Y-%m-%d %H:%M:%S'),
            "create_time": user.create_time.strftime('%Y-%m-%d %H:%M:%S')
        })

    return jsonify(errno=RET.OK, errmsg="修改成功", data=end)


@api.route('del_user', methods=["POST"])
def del_user():
    id = request.get_json().get('id')


    try:

        aim = db.session.query(User).get(id)

        db.session.delete(aim)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="删除用户表信息失败")

    try:
        data = db.session.query(User).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="用户表更新失败")

    end = []

    for user in data:
        end.append({
            "id": user.id,
            "name": user.name,
            "mobile": user.mobile,
            "power": user.power,
            "mail": user.mail,
            "login_time": user.login_time.strftime('%Y-%m-%d %H:%M:%S'),
            "create_time": user.create_time.strftime('%Y-%m-%d %H:%M:%S')
        })

    return jsonify(errno=RET.OK, errmsg="删除成功", data=end)


@api.route("getUserApply",  methods=["POST"])
def getUserApply():
    name = request.get_json().get('name')
    timePicker = request.get_json().get('timePicker')
    pagenation = request.get_json().get('pagenation')

    total=0

    # print("!!!!!!!!!", timePicker, pagenation)

    try:
        if name:
            if timePicker!=None:

                # 解析时间并转换为中国时区
                start_time = datetime.fromisoformat(timePicker[0].replace('Z', '+00:00')).astimezone(
                    pytz.timezone('Asia/Shanghai'))+timedelta(hours=24)
                end_time = datetime.fromisoformat(timePicker[1].replace('Z', '+00:00')).astimezone(
                    pytz.timezone('Asia/Shanghai'))+timedelta(hours=24)

                data = db.session.query(UserApply).filter(UserApply.handleResult=="NotProcessedYet",
                                                          UserApply.name==name,
                                                          UserApply.create_time.between(start_time, end_time)).offset((pagenation['current_page']-1)*pagenation['page_size']).limit(pagenation['page_size']).all()
                total = db.session.query(UserApply).filter(UserApply.handleResult=="NotProcessedYet",
                                                          UserApply.name==name,
                                                          UserApply.create_time.between(start_time, end_time)).count()
            else:
                data = db.session.query(UserApply).filter(UserApply.handleResult == "NotProcessedYet",
                                                          UserApply.name == name).offset((pagenation['current_page']-1)*pagenation['page_size']).limit(pagenation['page_size'])

                total = db.session.query(UserApply).filter(UserApply.handleResult == "NotProcessedYet",
                                                          UserApply.name == name).count()
        else:
            if timePicker!=None:
                # 解析时间并转换为中国时区
                start_time = datetime.fromisoformat(timePicker[0].replace('Z', '+00:00')).astimezone(
                    pytz.timezone('Asia/Shanghai'))+timedelta(hours=24)
                end_time = datetime.fromisoformat(timePicker[1].replace('Z', '+00:00')).astimezone(
                    pytz.timezone('Asia/Shanghai'))+timedelta(hours=24)

                data = db.session.query(UserApply).filter(UserApply.handleResult == "NotProcessedYet",
                                                          UserApply.create_time.between(start_time, end_time)).offset((pagenation['current_page']-1)*pagenation['page_size']).limit(pagenation['page_size'])

                total = db.session.query(UserApply).filter(UserApply.handleResult == "NotProcessedYet",
                                                          UserApply.create_time.between(start_time, end_time)).count()
            else:
                data = db.session.query(UserApply).filter(UserApply.handleResult == "NotProcessedYet").offset((pagenation['current_page']-1)*pagenation['page_size']).limit(pagenation['page_size']).all()
                total = db.session.query(UserApply).count()
    except Exception as e:
        db.session.rollback()  # 回滚数据库会话
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取用户信息失败")

    end = []

    for user in data:
        end.append({
            "id": user.id,
            "name": user.name,
            "mobile": user.mobile,
            "mail": user.mail,
            "password_hash": user.password_hash,
            "create_time": user.create_time.strftime('%Y-%m-%d %H:%M:%S')
        })

    outcome = {'tableData':end, 'total':total}

    return jsonify(errno=RET.OK, errmsg="查询成功", data=outcome)


@api.route("applyOk",  methods=["POST"])
def applyOk():
    id = request.get_json().get('id')

    try:
        aim = db.session.query(UserApply).filter(UserApply.id == id).first()
        new_user = User(name=aim.name, mobile=aim.mobile)
        new_user.copy_passwordHash(aim.password_hash)
        # new_user.password = 111

        aim.handleResult = "Agreed"
        db.session.add(new_user)

        db.session.commit()

    except Exception as e:
        db.session.rollback()  # 回滚数据库会话
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取用户信息失败")

    return jsonify(errno=RET.OK, errmsg="处理成功")


@api.route("applyReject", methods=["POST"])
def applyReject():
    id = request.get_json().get('id')

    try:
        aim = db.session.query(UserApply).filter(UserApply.id == id).first()

        aim.handleResult = "Rejected"

        db.session.commit()

    except Exception as e:
        db.session.rollback()  # 回滚数据库会话
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="处理用户信息失败")

    return jsonify(errno=RET.OK, errmsg="处理成功")
